<?php
namespace appin\cms\model;

use appin\cms\Model;
use think\model\concern\SoftDelete;

class Column extends Model
{
    use SoftDelete;

    protected $name = 'cms_column';
    protected $globalScope = ['UseLang'];
    protected $autoWriteTimestamp = true;
    protected $deleteTime = 'delete_time';
    public $mode = ['pages' => '单页', 'articles' => '文章'];
    public $status = [0 => '隐藏', 1 => '导航', 2 => '底部'];
    protected $append = ['mode_string','status_string','url'];

    /**
     * @param $query
     * @param $keyword
     */
    public function scopeUseKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->where('title', 'LIKE', '%'.$keyword.'%');
        }
    }

    /**
     * 栏目模型
     * @param $value
     * @param $data
     * @return mixed|string
     */
    public function getModeStringAttr($value, $data)
    {
        return isset($this->mode[$data['mode']]) ? $this->mode[$data['mode']] : '其他';
    }

    /**
     * 栏目位置
     * @param $value
     * @param $data
     * @return mixed|string
     */
    public function getStatusStringAttr($value, $data)
    {
        return isset($this->status[$data['status']]) ? $this->status[$data['status']] : '其他';
    }

    /**
     * @param $value
     * @param $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        if (isset($data['href']) && !empty($data['href']) ) {
            return $data['href'];
        }

        if ( isset($data['alias']) && $data['alias'] === 'index' ) {
            return '/';
        } elseif (isset($data['alias']) && empty($data['alias'])) {
            return '/'.$data['id'].'.html';
        } else {
            return '/'.$data['alias'].'.html';
        }
    }

    /**
     * 关联获取所有子栏目
     * @return \think\model\relation\HasMany
     */
    public function son()
    {
        return $this->hasMany(Column::class, 'pid', 'id');
    }

    /**
     * 根据条件列出所有的栏目
     * @param string $condition
     * @param bool $cache
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function lists($condition = '', $cache = false)
    {
        $lang_id = session('lang.id');
        return static::withoutGlobalScope()
            ->where('lang_id', $lang_id)
            ->UseWhere($condition)
            ->cache($cache)
            ->select();
    }
}